<!--
 * @Description: 第三方客户端弹出
 * @Author: chendingfengmail@163.com
 * @Date: 2021-11-08 08:39:12
 * @LastEditTime: 2022-01-17 13:57:47
 * @LastEditors: chendingfengmail@163.com
 * @Reference:
-->
<template>
  <el-dialog
    custom-class="clientDetailsHandle_dialog"
    :title="titleName"
    top="10vh"
    width="800px"
    height="800px"
    center
    :visible.sync="visible"
    :before-close="modelClose"
    @open="modelOpen"
    :close-on-click-modal="false"
    append-to-body>
    <el-form
      :rules="clientDetailsHandleRules"
      ref="clientDetailsHandleForm"
      :model="modelData"
      :disabled="formDisabled"
      v-loading="loading">
      <el-row :gutter="25">
        <el-col :span="12">
          <el-form-item label="厂家名称" :label-width="formLabelWidth" prop="manufacture">
            <el-input
              v-model="modelData.manufacture"
              maxlength="60"
              autocomplete="off"
              placeholder="请输入厂家名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系人" :label-width="formLabelWidth" prop="contact">
            <el-input
              v-model="modelData.contact"
              maxlength="60"
              autocomplete="off"
              placeholder="请输入联系人"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" :label-width="formLabelWidth" prop="telephone">
            <el-input v-model="modelData.telephone" autocomplete="off" placeholder="请输入联系电话"></el-input>
          </el-form-item>
          <el-form-item label="是否启用" :label-width="formLabelWidth" prop="enable">
            <el-switch v-model="modelData.enable" :active-value="1" :inactive-value="0" active-color="#13ce66">
            </el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="25">
        <el-col :span="12">
          <el-form-item label="客户appId" :label-width="formLabelWidth" prop="clientId">
            <el-input
              v-model="modelData.clientId"
              maxlength="60"
              autocomplete="off"
              placeholder="请输入客户appid"
              style="width:240px"
              :disabled="modelType !== 'add' ? true : false">
            </el-input>
            <el-button type="primary" class="button" icon="el-icon-refresh" @click="createAppId()" :disabled="modelType !== 'add'"></el-button>
          </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="客户密钥" :label-width="formLabelWidth" prop="clientSecret">
            <el-input
              v-model="modelData.clientSecret"
              maxlength="60"
              autocomplete="off"
              style="width:240px"
              :disabled="modelType !== 'info' ? false : true"
              placeholder="请输入客户秘钥并妥善保存">
            </el-input>
            <el-button type="primary" class="button" icon="el-icon-refresh" @click="createAppSecret()" :disabled="modelType === 'info'"></el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="25">
        <el-col :span="12">
          <el-form-item label="令牌有效期" :label-width="formLabelWidth" prop="accessTokenValidity">
            <el-input
              v-model="modelData.accessTokenValidity"
              autocomplete="off"
              placeholder="单位秒">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="刷新有效期" :label-width="formLabelWidth" prop="refreshTokenValidity">
            <el-input
              v-model="modelData.refreshTokenValidity"
              autocomplete="off"
              placeholder="单位秒">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="25">
        <el-col :span="12">
          <el-form-item v-for="(item, index) in modelData.scopeList"
            class="group-item"
            :key="item.index"
            :label="item.index == 0 ? '可访问范围' : ''"
            :label-width="formLabelWidth"
            :prop="'scopeList.' + index + '.scope'"
            :rules="[{required: true, message: '请输入访问范围', trigger: 'blur'},{pattern:/^([\u4e00-\u9fa5]|[\w-])+$/, message: '只能输入中文 | 英文 | 数字 | 横线 | 下划线', trigger: 'blur'}]">
            <el-input
              v-model="item.scope"
              autocomplete="off"
              placeholder="请输入访问范围">
              <template v-if="modelType != 'info'">
                <el-button v-if="item.index == 0" slot="append" icon="el-icon-plus" @click="addItem('scope')"></el-button>
                <el-button v-else slot="append" icon="el-icon-minus" @click="delItem('scope', item)"></el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-for="(item,index) in modelData.resourceIdsList"
            :key="item.index"
            class="group-item"
            :label="item.index == 0 ? '可访问资源' : ''"
            :label-width="formLabelWidth"
            :prop="'resourceIdsList.'+index+'.resourceIds'"
            :rules="[{required: true, message: '请输入资源列表', trigger: 'blur'},{pattern:/^([\u4e00-\u9fa5]|[\w-])+$/, message: '只能输入中文 | 英文 | 数字 | 横线 | 下划线', trigger: 'blur'}]">
            <el-input
              v-model="item.resourceIds"
              autocomplete="off"
              placeholder="请输入资源列表">
              <template v-if="modelType != 'info'">
                <el-button v-if="item.index == 0" slot="append" icon="el-icon-plus" @click="addItem('resourceIds')"></el-button>
                <el-button v-else slot="append" icon="el-icon-minus" @click="delItem('resourceIds', item)"></el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="25">
        <el-col :span="12">
          <el-form-item label="md5加盐值" :label-width="formLabelWidth" prop="saltValue">
            <el-input
              v-model="modelData.saltValue"
              autocomplete="off"
              placeholder="请输入盐值">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="加盐顺序" :label-width="formLabelWidth">
            <el-select v-model="modelData.saltOrder" placeholder="请选择加盐顺序" style="width:100%;" prop="saltOrder">
              <el-option v-for="item of ORDERS" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="0">
        <el-col :span="24">
          <el-form-item label="客户权限" :label-width="formLabelWidth" prop="authorities">
            <el-input
              v-model="authorities"
              maxlength="60"
              autocomplete="off"
              style="width:630px"
              :disabled="true"
              placeholder="请选择客户初始权限">
            </el-input>
            <el-button size="samll" type="primary" style="margin-top: 5px;" class="button icon iconfont icon-jia" @click="showRightDialog()"></el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注信息" :label-width="formLabelWidth" prop="remark">
        <el-input
          type="textarea"
          maxlength="120"
          :rows="1"
          v-model="modelData.remark"
          autocomplete="off"
          placeholder="请输入备注信息">
        </el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" v-show="btnVisible">
      <el-button type="primary" @click="formSubmit" :loading="loading">提 交</el-button>
    </div>
    <ClientRightDialog :visible.sync="rightDialogVisible" :modelData="modelData" @select="selectRights"></ClientRightDialog>
  </el-dialog>
</template>

<script>
import util from '@/libs/util';
import ClientRightDialog from './clientRightDialog.vue';

export default {
  name: 'clientDetailsHandleDialog',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    modelType: {
      type: String,
      required: true,
      default: () => {
        return 'info';
      },
    },
    modelData: {
      type: Object,
      default: () => {
        return {
          manufacture: '',
          contact: '',
          telephone: '',
          enable: 1,
          clientId: '',
          accessTokenValidity: 7200,
          refreshTokenValidity: 604800,
          clientSecret: '',
          resourceIds: '',
          scope: '',
          remark: '',
          authorities: '',
          resourceIdsList: [{ resourceIds: 'gate_way_server', index: 0 }],
          scopeList: [{ scope: 'user_info', index: 0 }],
          saltOrder: 1,
          saltValue: "dondown",
        };
      },
    },
  },
  components: {
    ClientRightDialog
  },
  data() {
    return {
      titleName: '详情',
      formLabelWidth: '100px',
      dialogFormVisible: false,
      formDisabled: false,
      btnVisible: true,
      loading: false,
      clientList: [],
      rightDialogVisible: false,
      authorities: '',
      clientDetailsHandleRules: {
        manufacture: this.$Validate.otherTxt(true, '请输入厂家名称'),
        contact: this.$Validate.otherTxt(true, '请输入联系人'),
        telephone: this.$Validate.mobile(true, '请输入联系电话'),
        clientId: this.$Validate.idNumber(true, '请输入接入appId'),
        clientSecret: this.$Validate.idNumber(true, '请输入接入app密钥'),
        accessTokenValidity: this.$Validate.integer(true, '请输入令牌有效期'),
        refreshTokenValidity: this.$Validate.integer(true, '请输入令牌有效期'),
      },
      ORDERS: [
        {label: "向前加盐", value: 0},
        {label: "向后加盐", value: 1}
      ]
    };
  },
  created() {},
  computed: {},
  mounted() {},
  methods: {
    // appid生成
    createAppId(){
      this.modelData.clientId = util.generateUUID();
    },

    // secret生成
    createAppSecret(){
      this.$nextTick(x => {
        this.modelData.clientSecret = util.generateUUID();
        this.$forceUpdate();
      });
    },

    // 显示权限对话框
    showRightDialog(){
      this.rightDialogVisible = true;
    },

    // 选择权限列表
    selectRights(rights) {
      let names = [];
      let ids = [];
      rights.forEach(item => {
        names.push(item.label);
        ids.push(item.id);
      });
      this.authorities = names.toString();
      this.modelData.authorities = ids.toString();
      console.log('authorities', this.authorities);
    },

    // 对话框打开
    modelOpen() {
      this.loadClientDeatilsList();
      switch (this.modelType) {
        case 'add':
          this.modelTypeChange('客户端接入信息添加', false, true);
          break;
        case 'info':
          this.modelTypeChange('客户端接入信息详情', true, false);
          this.listInfo(this.modelData);
          break;
        case 'edit':
          this.modelTypeChange('客户端接入信息编辑', false, true);
          this.listInfo(this.modelData);
          break;
        default:
          break;
      }
    },

    // 模式切换
    modelTypeChange(titleName, formDisabled, btnVisible) {
      this.titleName = titleName;
      this.formDisabled = formDisabled;
      this.btnVisible = btnVisible;
    },

    listInfo(data) {
      if(data.resourceIds && data.resourceIds != null) {
        let resourceIds = data.resourceIds;
        if(resourceIds.indexOf(',') == -1) {
          this.modelData.resourceIdsList.push({ resourceIds: resourceIds, index: 0})
        } else {
          let resourceIdsArr = resourceIds.split(',');
          let index_1 = 0;
          resourceIdsArr.forEach(item => {
            this.modelData.resourceIdsList.push({ resourceIds: item, index: index_1});
            index_1++;
          })
        }
      }
      if(data.scope && data.scope != null) {
        let scope = data.scope;
        if(scope.indexOf(',') == -1) {
          this.modelData.scopeList.push({ scope: scope, index: 0})
        } else {
          let scopeArr = scope.split(',');
          let index_2 = 0;
          scopeArr.forEach(item => {
            this.modelData.scopeList.push({ scope: item, index: index_2});
            index_2++;
          })
        }
      }
    },

    // 动态增加列表item
    addItem(itemType) {
      switch(itemType) {
        case 'resourceIds':
          // 获取最后数组中 最后一个属性的 index
          let maxResourceIdsIndex = this.modelData.resourceIdsList[this.modelData.resourceIdsList.length - 1].index;
          this.modelData.resourceIdsList.push({ resourceIds: '', index: maxResourceIdsIndex + 1});
          break;
        case 'scope':
          let maxScopeIndex = this.modelData.scopeList[this.modelData.scopeList.length - 1].index;
          this.modelData.scopeList.push({ scope: '', index: maxScopeIndex + 1});
          break;
        default:
          break;
      }
    },

    // 动态删减列表item
    delItem(itemType, item) {
      switch(itemType) {
        case 'resourceIds':
          // 获取删除元素的下标
          let delResourceIdsIndex = util.arrIndex(this.modelData.resourceIdsList, item);
          this.modelData.resourceIdsList.splice(delResourceIdsIndex, 1);
          break;
        case 'scope':
          let delScopeIndex = util.arrIndex(this.modelData.scopeList, item);
          this.modelData.scopeList.splice(delScopeIndex, 1);
          break;
        default:
          break;
      }
    },

    // 表单提交
    formSubmit() {
      this.$refs.clientDetailsHandleForm.validate((valid) => {
        this.modelData.id = this.modelData.clientId;
        this.modelData.authorizedGrantTypes = 'authorization_code,refresh_token,implicit,password,client_credentials';
        this.modelData.autoapprove = true;
        // 处理资源列表数据
        let resourceIds = '';
        this.modelData.resourceIdsList.forEach(item => {
          if(item.resourceIds != '') {
            if(item.index == 0) {
              resourceIds = item.resourceIds;
            } else {
              resourceIds += ',' + item.resourceIds;
            }
          }
        });
        this.modelData.resourceIds = resourceIds;
        // 处理访问范围数据
        let scope = '';
        this.modelData.scopeList.forEach(item => {
          if(item.scope != '') {
            if(item.index == 0) {
              scope = item.scope;
            } else {
              scope += ',' + item.scope;
            }
          }
        });
        this.modelData.scope = scope;
        if (valid) {
          switch (this.modelType) {
            case 'add':
              this.handleAdd(this.modelData);
              break;
            case 'edit':
              this.handleEdit(this.modelData);
              break;
            default:
              break;
          }
        }
      });
    },

    // 加载第三方客户列表
    async loadClientDeatilsList() {
      let param = {
        pageIndex: 1,
        pageSize: 9999,
      };
      try {
        let result = await this.$api.clientDetails.findList(param);
        this.clientList = result.value;
      } catch (error) {
        console.log(error);
      }
    },

    // 新增
    handleAdd(formData) {
      this.loading = true;
      let appIdValid = this.clientList.find((item) => item.clientId == formData.clientId);
      if (appIdValid) {
        this.$message.warning('该appId已存在');
        this.loading = false;
      } else {
        this.$api.clientDetails
          .add(formData)
          .then((res) => {
            this.$message.success('添加成功');
            this.loading = false;
            // 保存到txt文件
            util.commons.saveAsClientDetails(this.modelData, 'txt');
            this.modelClose();
            this.$emit('loadList');
          })
          .catch((err) => {
            console.log(err);
            this.loading = false;
          });
      }
    },
    // 编辑
    handleEdit(formData) {
      this.loading = true;
      this.$api.clientDetails
        .update(formData)
        .then((res) => {
          this.$message.success('更新成功');
          this.loading = false;
          this.modelClose();
          this.$emit('loadList');
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
    },
    // 重置表单
    resetForm() {
      this.$nextTick(() => {
        this.$refs.clientDetailsHandleForm.resetFields();
      });
    },
    // 对话框关闭
    modelClose() {
      this.resetForm();
      this.$emit('update:visible', false); // 直接修改父组件的属性
    },
  },
};
</script>

<style lang="scss">
.clientDetailsHandle_dialog {
  .el-dialog__body {
    max-height: 70vh !important;
  }
  .button{
    margin-top: 1px;
    padding-left: 2px;
    padding-right: 10px;
    padding-top: 9px;
    width: 20px;
    height: 35px;
  }
  //滚动条的宽度
  ::-webkit-scrollbar {
    display: block;
    width: 0.375rem;
    border-radius: 0.625rem;
  }
  //滚动条的滑块
  ::-webkit-scrollbar-thumb {
    border-radius: 0.625rem;
  }
}
</style>
